//
//  CCRefreshControl.swift
//  CXCWeibo
//
//  Created by cxc on 15/7/4.
//  Copyright © 2015年 china. All rights reserved.
//

import UIKit
import FFAutoLayout

class CCRefreshControl: UIRefreshControl {
    override init() {
        super.init()
        addSubview(refreshView)
        refreshView.ff_AlignInner(ff_AlignType.CenterCenter, referView: self, size: CGSize(width: 150, height: 60))
        addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions(rawValue:0), context: nil)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    deinit{
        removeObserver(self, forKeyPath: "frame")
    }

    /// 显示提示图标标记
    private var showTipFlag = false
    private var loadingFlag = false
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [NSObject : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        if frame.origin.y > 0{
            return
        }
        if refreshing && !loadingFlag{
            refreshView.startLoadingAnimation()
            loadingFlag = true
            return
        }
        if frame.origin.y < -50 && !showTipFlag{
            showTipFlag = true
            refreshView.rotateTipIcon(showTipFlag)
        } else if frame.origin.y >= -50 && showTipFlag{
            showTipFlag = false
            refreshView.rotateTipIcon(showTipFlag)
        }
    }
    override func endRefreshing() {
        super.endRefreshing()
        refreshView.stopAnimation()
        loadingFlag = false
    }
    // MARK: - 懒加载控件
    lazy var refreshView = CCRefreshView.refreshView()
}

class CCRefreshView:UIView {
    @IBOutlet weak var tipView: UIView!
    @IBOutlet weak var loadingIcon: UIImageView!
    @IBOutlet weak var pullIcon: UIImageView!
    
    /**
    *  实现一个类方法
    */
    class func refreshView() -> CCRefreshView {
        return NSBundle.mainBundle().loadNibNamed("CCRefreshView", owner: nil, options: nil).last as! CCRefreshView
    }
    
    private func rotateTipIcon(clockWise:Bool){
        var angle = M_PI
        angle += clockWise ? -0.01 : 0.01
        UIView.animateWithDuration(0.5) { () -> Void in
            self.pullIcon.transform = CGAffineTransformRotate(self.pullIcon.transform,CGFloat(angle))
        }
    }
    /**
    *  开始动画
    */
    private func startLoadingAnimation(){
        tipView.hidden = true
        let animation = CABasicAnimation()
        animation.toValue = 2 * M_PI
        animation.repeatCount = MAXFLOAT
        animation.duration = 0.5
        loadingIcon.layer.addAnimation(animation, forKey: nil)
    }
    /**
    *  停止动画
    */
    private func stopAnimation(){
        tipView.hidden = false
        loadingIcon.layer.removeAllAnimations()
    }
    
}